const crypto = require("crypto"); // 加密模块
const Page = require("../models/page");
const User = require("../models/user");
const { returnFn } = require("../config/returnFn");

const checkRootLogin = (req, res, next) => {
    if (!req.session.employee) {
        return returnFn(res, 400, "未登录");
    }
    next();
}
const checkUserLogin = (req, res, next) => {
    console.log('req.session.user: =>' + JSON.stringify(req.session.user));
    if (!req.session.user) {
        return returnFn(res, 400, "未登录");
    }
    next();
}

const register = (req, res) => {
    if (!req.session.vCode || req.session.vCode != req.body.vCode) return returnFn(res, 401, "验证码错误");
    if (!req.body.username) return returnFn(res, 402, "用户名不能为空");
    if (!req.body.password) return returnFn(res, 402, "密码不能为空");
    if (!req.body.mobile) return returnFn(res, 402, "手机号码不能为空");

    // 密码加密
    let md5 = crypto.createHash("md5");
    let password = md5.update(req.body.password).digest("base64");

    let newUser = new User({
        username: req.body.username,
        password: password,
        mobile: req.body.mobile,
        isDelete: 1
    });

    User.getUserByName(req.body.username, (err, result) => {
        if (err) return returnFn(res, 503, "数据库异常");
        if (result.length > 0) return returnFn(res, 403, "用户名已经存在");
        else {
            User.getUserByMobile(req.body.mobile, (err, result) => {
                if (err) return returnFn(res, 503, "数据库异常！");
                if (result.length > 0) return returnFn(res, 403, "手机号已注册过");
                else {
                    User.addUser(newUser, (err, data) => {
                        if (err) return returnFn(res, 503, "数据库异常");
                        newUser.id = data.insertId;
                        req.session.user = newUser;
                        res.send({
                            "success": true
                        });
                    });
                }
            });
        }
    });
}

const login = (req, res) => {
    let md5 = crypto.createHash("md5");
    let password = md5.update(req.body.password).digest("base64");
    User.getUserByName(req.body.username, (err, result) => {
        if (!err) {
            if (result.length == 0) return returnFn(res, 404, "用户名不存在");
            if (result[0].password != password) return returnFn(res, 401, "密码错误");
            req.session.user = result[0];
            console.log('req.session.user: =>' + JSON.stringify(req.session.user));
            res.send({
                "success": true
            });
        }
    })
}
const logout = (req, res) => {
    req.session.user = null;
    res.send({
        "success": true
    })
}
const updatePassword = (req, res) => {
    console.log(req.session.vCodePassword);
    console.log(req.body.vCode);
    if (!req.session.vCodePassword || req.session.vCodePassword != req.body.vCode) {
        return returnFn(res, 401, "验证码错误");
    }
    let md51 = crypto.createHash("md5");
    let oldPassword = md51.update(req.body.oldPassword).digest("base64");
    let md52 = crypto.createHash("md5");
    let newPassword = md52.update(req.body.newPassword).digest("base64");
    let id = req.session.user.id;
    User.getUserById(id, (err, result) => {
        if (result.password != oldPassword) return returnFn(res, 401, "密码错误");
        User.updatePassword(id, newPassword, (err, result) => {
            if (err) return returnFn(res, 503, "数据库异常");
            req.session.user = null;
            res.send({
                "success": true
            });
        });
    });
}
const queryUserMessage = (req, res) => {
    User.queryUserMessage(req.session.user.id, (err, result) => {
        if (err) return returnFn(res, 503, "数据库异常");
        res.send(result)
    });
}

const createCode = () => {
    let code = "";
    let codeLength = 6; //验证码的长度   
    let random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); //随机数  
    for (let i = 0; i < codeLength; i++) { //循环操作  
        let index = Math.floor(Math.random() * 10); //取得随机数的索引（0~35）  
        code += random[index]; //根据索引取得随机数加到code上  
    }
    return code;
}
const vCode = (req, res) => {
    let code = createCode();
    req.session.vCode = code;
    res.send({
        "vCode": code
    });
}
const vCodeForUpdatePassword = (req, res) => {
    let code = createCode();
    req.session.vCodePassword = code;
    res.send({
        "vCode": code
    });
}

const queryUser = (req, res) => {
    let page = new Page({
        page: req.query.page ? parseInt(req.query.page) : 0,
        size: req.query.size ? parseInt(req.query.size) : 10,
    });
    User.queryUser(page, function(err, data) {
        if (err) return returnFn(res, 503, "数据库异常");
        User.countUser(function(err, result) {
            if (err) return returnFn(res, 503, "数据库异常");
            page.total = result.count;
            page.rows = data;
            returnFn(res, 200, "", page)
        })
    })
}

const updateUser = (req, res) => {
    let newUser = new User({
        id: req.body.id,
        isDelete: req.body.isDelete
    });
    User.updateUser(newUser, (err, result) => {
        if (err) return returnFn(res, 503, "数据库异常");
        res.send({
            "success": true
        })
    })
}

module.exports = {
    checkRootLogin,
    checkUserLogin,
    register,
    login,
    logout,
    updatePassword,
    queryUserMessage,
    vCode,
    vCodeForUpdatePassword,
    queryUser,
    updateUser
}